package com.copera.cn.kaka;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.copera.cn.kaka.adapter.ExchangeRuleAdapter;
import com.copera.cn.kaka.util.ActionUrls;
import com.copera.cn.kaka.util.HttpUtils;
import com.copera.cn.kaka.vo.ExchangeRuleVo;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class CardExchangeActivity extends BaseActivity {
	
	private RelativeLayout back;
	private EditText editText1,editText2;
	private Button loginButton;
	private ListView lv;
	private ProgressDialog dialog;
	private Handler handler;
	private String ruleId = null;
	private ExchangeRuleAdapter exchangeRuleAdapter;
	List<ExchangeRuleVo> list = new ArrayList<ExchangeRuleVo>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		refreshView(getLayoutInflater().inflate(R.layout.card_exchange_rule, null));
		initViews();
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {

				case ActionUrls.FAILURE:
					Toast.makeText(CardExchangeActivity.this, (String) msg.obj,
							Toast.LENGTH_SHORT).show();
					break;
				case 12:
					ruleId = msg.obj.toString();
					dialogConfirm();
				}
			}
		};		
		initEvent();
		//强制为竖屏 
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}
	private void delete() {
		new Thread() {
			public void run() {
				try {
					String json = HttpUtils.get(ActionUrls.URL_DELETERULE + "?ruleId=" + ruleId + "&shopId=" + getAppCustomer().getShop().getShopId(), getAppCustomer().getHttpClient());
					JSONObject jo = new JSONObject(json);
					String message = jo.getString("message");
					if("删除成功".equals(message)){
						Intent intent = new Intent(CardExchangeActivity.this,CardExchangeActivity.class);
						startActivity(intent);
						finish();
						Message msg = handler.obtainMessage(ActionUrls.FAILURE, message);
						handler.sendMessage(msg);
					}else{
						Message msg = handler.obtainMessage(ActionUrls.FAILURE, message);
						handler.sendMessage(msg);
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			};
		}.start();				
	}
	
	@Override
	protected void onResume() {
		list = new ArrayList<ExchangeRuleVo>();
		list = findRule();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
		exchangeRuleAdapter = new ExchangeRuleAdapter(getAppCustomer(), list, this, handler);
		lv.setAdapter(exchangeRuleAdapter);
		exchangeRuleAdapter.notifyDataSetChanged();
		super.onResume();
	}
	private void dialogConfirm() {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				CardExchangeActivity.this);
		builder.setTitle("删除");
		builder.setMessage("确定要删除吗？");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				delete();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		builder.create().show();
	}
	
	private void initViews(){
		back = (RelativeLayout) findViewById(R.id.back);
		editText1 = (EditText) findViewById(R.id.et_name);
		editText2 = (EditText) findViewById(R.id.EditText01);
		loginButton = (Button) findViewById(R.id.button2);
		lv = (ListView)findViewById(R.id.ruleList);
		dialog=getpDialog(this);
	}
	
	private void initEvent(){
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(CardExchangeActivity.this,MipcaActivityCapture.class);
				Bundle bundle = new Bundle();
				bundle.putString("type", "rule");
				intent.putExtras(bundle);
			    startActivity(intent);
			}
		});
		loginButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isVilid()){
				new Thread() {
					public void run() {
						try {
							String str = editText2.getText().toString();
							str = changeToUnicode(str);
							String json = HttpUtils.get(ActionUrls.URL_EXCHANGERULE_SAVE+"?id="+getAppCustomer().getShop().getShopId()+"&userName="+editText1.getText()+"&userPass="+str, getAppCustomer().getHttpClient());
							JSONObject jo = new JSONObject(json);
							String message = jo.getString("message");
							if("保存成功".equals(message)){
								Intent intent = new Intent(CardExchangeActivity.this,CardExchangeActivity.class);
								startActivity(intent);
								finish();
								Message msg = handler.obtainMessage(ActionUrls.FAILURE, message);
								handler.sendMessage(msg);
							}else{
								Message msg = handler.obtainMessage(ActionUrls.FAILURE, message);
								handler.sendMessage(msg);
							}
						} catch (ClientProtocolException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					};
				}.start();				
				}	
			}
		});	
		
	}
	
	private List<ExchangeRuleVo> findRule(){
		new Thread() {
			public void run() {
				try {
					String json = HttpUtils.get(ActionUrls.URL_EXCHANGERULE1_LIST+"?id="+getAppCustomer().getShop().getShopId(), getAppCustomer().getHttpClient());
					JSONObject jo = new JSONObject(json);
					JSONArray jsonArr = jo.getJSONArray("list");
					if (jsonArr != null && jsonArr.length() > 0) {
						for (int i = 0; i < jsonArr.length(); i++) {
							JSONObject object = jsonArr.getJSONObject(i);
							ExchangeRuleVo vo = new ExchangeRuleVo();
							vo.setPointCount(object.getString("pointCount"));
							vo.setExchangeContent(object.getString("exchangeContent"));
							vo.setId(object.getString("id"));
							list.add(vo);
						}
						getAppCustomer().getShop().setRuleList(list);
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			};
		}.start();				
			return 	list;	
	}
	private boolean isVilid(){
		if (editText1.getText().toString() == null || "".equals(editText1.getText().toString().trim())) {
			Toast.makeText(CardExchangeActivity.this, "卡点数不能为空", Toast.LENGTH_SHORT).show();
			return false;
		}else if(editText1.getText().toString().length()>2){
			Toast.makeText(CardExchangeActivity.this, "卡点数不能超过2位数字", Toast.LENGTH_SHORT).show();
			return false;			
		}
		if (editText2.getText().toString() == null || "".equals(editText2.getText().toString().trim())) {
			Toast.makeText(CardExchangeActivity.this, "兑换物品不能为空", Toast.LENGTH_SHORT).show();
			return false;
		}else if(editText2.getText().toString().length()>10){
			Toast.makeText(CardExchangeActivity.this, "兑换物品字数要求少于10个", Toast.LENGTH_SHORT).show();
			return false;			
		}
		
		return true;
	}
	
}
